package demo.android.ipc;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hss01248.facedetect.BaseURL;
import com.hss01248.facedetect.CheckType;
import com.hss01248.facedetect.activity.CollectActivity;
import com.hss01248.facedetect.response.CheckTicketResponse;
import com.hss01248.facedetect.utils.IdNumberUtils;
import com.hss01248.facedetect.utils.MyProgressUtils;
import com.hss01248.facedetect.utils.SHExtends;
import com.hss01248.facedetect.utils.SPUtils;
import com.hss01248.facedetect.utils.ToastUtil;
import com.hss01248.facedetect.utils.httpUtils;
import com.zkteco.android.biometric.core.device.ParameterHelper;
import com.zkteco.android.biometric.core.device.TransportType;
import com.zkteco.android.biometric.core.utils.LogHelper;
import com.zkteco.android.biometric.module.idcard.IDCardReader;
import com.zkteco.android.biometric.module.idcard.IDCardReaderFactory;
import com.zkteco.android.biometric.module.idcard.exception.IDCardReaderException;
import com.zkteco.android.biometric.module.idcard.meta.IDCardInfo;
import com.zkteco.android.biometric.module.idcard.meta.IDPRPCardInfo;


import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import demo.android.ipc.custom_keyboard.CustomKeyboard;
import demo.android.ipc.custom_keyboard.MyKeyboardView;


public class MainActivity extends AppCompatActivity {


    private TextView tv_ticketNo;
    private TextView tv_message;
    private TextView tv_idcardNO;
    private int requestCode_19 = 19;
    private ImageView img_result;
    private Button ma_btn_sure;
    private long exitTime;
    private String idNumber2;
    private TextView tv_count;
    private int count;
    private boolean once = true;
    private long idcard_exitTime;


    /**********************语音合成**********************/
//语音引擎
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {
                Log.i(TAG, "onInit: TTS引擎初始化成功");
            } else {
                Log.i(TAG, "onInit: TTS引擎初始化失败");
            }
        }
    }

    private static final String TAG = "PhoneActivity";
    private TextToSpeech mSpeech = null;
    private static float m_voice_speed = 1.2f;   //合成语音的语速
    private static float m_voice_pitch = 1.0f;   //合成语音的语调
    /****************************************************/


    Handler handler_work;


    private static final int VID = 1024;    //IDR VID
    private static final int PID = 50010;     //IDR PID


    private IDCardReader idCardReader = null;
    private TextView textView = null;
    private ImageView imageView = null;
    private boolean bopen = false;
    private BarcodeScannerResolver mBarcodeScannerResolver;

    Bitmap bitmap_idPhoto = null;
    File idPhotoPath;
    String idNumber = null;
//    String saveIDString = "非空";
    String saveIDString ;

    private EditText writebankcard_mobileedit;
    CustomKeyboard mCustomKeyboard;
    private long barcode_exitTime;

    String pauseBarcode = "";

    private SHExtends she;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE); // 去掉标题栏 有效
        setContentView(R.layout.activity_main);

        handler_work = new Handler();
        textView = (TextView) findViewById(R.id.textView);
        imageView = (ImageView) findViewById(R.id.imageView);
        tv_ticketNo = (TextView) findViewById(R.id.ma_tv_ticketNo);
        tv_message = (TextView) findViewById(R.id.ma_tv_message);
        tv_count = (TextView) findViewById(R.id.ma_tv_personCount);
        tv_idcardNO = (TextView) findViewById(R.id.ma_tv_idCardNO);
        img_result = (ImageView) findViewById(R.id.ma_img_result);
        writebankcard_mobileedit = (EditText) findViewById(R.id.ma_writebankcard_mobileedit);
        ma_btn_sure = (Button) findViewById(R.id.ma_btn_sure);
        ma_btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((System.currentTimeMillis() - exitTime) > 2000) {

                    idCheck();

                    exitTime = System.currentTimeMillis();

                } else {

                    ToastUtil.showToast("请2秒后再点击");
                }

            }
        });

        //1 屏蔽掉系统默认输入法
        if (Build.VERSION.SDK_INT <= 10) {
            writebankcard_mobileedit.setInputType(InputType.TYPE_NULL);
        } else {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            try {
                Class<EditText> cls = EditText.class;
                Method setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(writebankcard_mobileedit, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //2 初试化键盘
        MyKeyboardView keyboardView = (MyKeyboardView) findViewById(R.id.ma_customKeyboard);
        mCustomKeyboard = new CustomKeyboard(MainActivity.this, keyboardView, writebankcard_mobileedit);
        mCustomKeyboard.showKeyboard();

        writebankcard_mobileedit.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mCustomKeyboard.showKeyboard();
                return false;
            }
        });
        writebankcard_mobileedit.clearFocus();


        startIDCardReader();

        mBarcodeScannerResolver = new BarcodeScannerResolver();
        mBarcodeScannerResolver.setScanSuccessListener(new BarcodeScannerResolver.OnScanSuccessListener() {
            @Override
            public void onScanSuccess(String barcode) {
                tv_ticketNo.setText(barcode);
                Log.d("barcode", barcode);

                if (barcode.trim().length() > 0) {
                    if ((System.currentTimeMillis() - barcode_exitTime) > 2000) {

                        barcode_exitTime = System.currentTimeMillis();

                        checkTicket(CheckType.TYPE_QRCODE, barcode, String.valueOf(SPUtils.get(MainActivity.this, "CHECK_TICKET_TERMINAL_N0", "")));

                    } else {
                        ToastUtil.showToast("请2秒后再操作");
                    }
                }

            }
        });

        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        idPhotoPath = new File(dir, "idPhoto" + ".jpg");

        if (!idPhotoPath.exists()) {
            try {
                idPhotoPath.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


//        开启身份证读卡器
        openIDReader();


        mSpeech = new TextToSpeech(MainActivity.this, new TTSListener());

        initBote();

    }

    private void initBote() {

        try {
            she = new SHExtends("/dev/ttyS3", "9600");
            she.open();
        } catch (Exception e) {
            ToastUtil.showToast("灯带Com口异常：" + e.getMessage());
            e.printStackTrace();
        }
    }

    //播放合成语音
    public void PlayAudioFile(String str) {
        //设置中文
        int supported = mSpeech.setLanguage(Locale.CHINA);
        mSpeech.setSpeechRate(m_voice_speed);
        mSpeech.setPitch(m_voice_pitch);

        if ((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
            //语言设置失败
            Log.i(TAG, "中文设置失败");
        } else {
            Log.i(TAG, "中文设置成功");
        }
        //mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
        mSpeech.speak(str, TextToSpeech.QUEUE_ADD, null);

    }

    void idCheck() {
        String idNumber = writebankcard_mobileedit.getText().toString().trim();
        if (idNumber == "") {
            ToastUtil.showToast("请输入身份证号");
            return;
        }
        if (IdNumberUtils.isIdNumber(idNumber)) {
            checkTicket(CheckType.TYPE_IDCARD, idNumber, String.valueOf(SPUtils.get(MainActivity.this, "CHECK_TICKET_TERMINAL_N0", "")));
        } else {
            ToastUtil.showToast("请输入合法的身份证");
        }
    }

    private void startIDCardReader() {
        // Define output log level
        LogHelper.setLevel(Log.VERBOSE);
        // Start fingerprint sensor

        Map idrparams = new HashMap();

        idrparams.put(ParameterHelper.PARAM_KEY_VID, VID);
        idrparams.put(ParameterHelper.PARAM_KEY_PID, PID);
        idCardReader = IDCardReaderFactory.createIDCardReader(this, TransportType.USB, idrparams);


    }


    void openIDReader() {
        try {
            if (bopen) return;
            idCardReader.open(0);
            bopen = true;
            textView.setText("连接设备成功");
        } catch (IDCardReaderException e) {
            textView.setText("连接设备成功");
            LogHelper.d("连接设备失败, 错误码：" + e.getErrorCode() + "\n错误信息：" + e.getMessage() + "\n 内部错误码=" + e.getInternalErrorCode());
        }
    }


    public void OnBnClose(View view) {
        try {
            if (bopen) {
                idCardReader.close(0);
                bopen = false;
            }
            textView.setText("关闭设备成功");
        } catch (IDCardReaderException e) {
            textView.setText("关闭设备失败");
            LogHelper.d("关闭设备失败, 错误码：" + e.getErrorCode() + "\n错误信息：" + e.getMessage() + "\n 内部错误码=" + e.getInternalErrorCode());
        }
    }

    public void OnBnGetSamID(View view) {
        try {
            if (!bopen) {
                textView.setText("请先连接设备");
            }
            String samid = idCardReader.getSAMID(0);
            textView.setText("获取SAM编号成功：" + samid);
        } catch (IDCardReaderException e) {
            textView.setText("获取SAM编号失败");
            LogHelper.d("获取SAM模块失败, 错误码：" + e.getErrorCode() + "\n错误信息：" + e.getMessage() + "\n 内部错误码=" + e.getInternalErrorCode());
        }
    }


    private void showMessage(String string) {
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage(string)
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(
                                    DialogInterface dialoginterface, int i) {
                            }
                        }).show();
    }

    private int index = 0;

    public String printHexString(byte[] b) {
        String a = "";
        for (int i = 0; i < 1024; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }

            a = a + hex;
        }

        return a;
    }

    public void Authenticate() {
        try {
            idCardReader.findCard(0);
            idCardReader.selectCard(0);
        } catch (IDCardReaderException e) {
            e.printStackTrace();
        }
    }


    void readIDCard() {
        try {


            if (!bopen) {
//                textView.setText("请先连接设备");
            }
            Authenticate();
            int ret = idCardReader.readCardEx(0, 1);
            if (1 == ret) {
                IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
//                textView.setText("timeSet:" + (nTickRead - nTickStart)
                // + "姓名：" + idCardInfo.getName()
                // + "，民族：" + idCardInfo.getNation()
                // + "，住址：" + idCardInfo.getAddress()
                // + ",身份证号：" + idCardInfo.getId());
                if (null != idCardInfo) {
                    idNumber = idCardInfo.getId();
                }
                Log.d("shoot", "" + idNumber);

            } else if (2 == ret) {
                IDPRPCardInfo idprpCardInfo = idCardReader.getLastPRPIDCardInfo();
//                textView.setText("timeSet:" + (nTickRead - nTickStart)
                // + "英文名：" + idprpCardInfo.getEnName()
                // + "，中文名：" + idprpCardInfo.getCnName()
                // +"，国家：" + idprpCardInfo.getCountry()
                // + ",证件号：" + idprpCardInfo.getId());
                if (null != idprpCardInfo) {

                    idNumber = idprpCardInfo.getId();
                }

            }

            //身份证不同才可以连刷
            //同一身份证3s后可再刷
            try {
                //&& (!(saveIDString.equals(idNumber)))
//                && (!TextUtils.isEmpty(saveIDString))
//
                if (!TextUtils.isEmpty(idNumber) ) {

                    if (idNumber.equals(saveIDString) && (System.currentTimeMillis() - idcard_exitTime) > 3000) {

                        checkTicket(CheckType.TYPE_IDCARD, idNumber, String.valueOf(SPUtils.get(MainActivity.this, "CHECK_TICKET_TERMINAL_N0", "")));

                        idcard_exitTime = System.currentTimeMillis();//记录读取时间

//                        Log.d("count333333333333", ("" + count++) + "，idNumber:" + idNumber + "，saveIDString:" + saveIDString);

                    } else {
                        if (!idNumber.equals(saveIDString)) {
                            checkTicket(CheckType.TYPE_IDCARD, idNumber, String.valueOf(SPUtils.get(MainActivity.this, "CHECK_TICKET_TERMINAL_N0", "")));

//                            Log.d("count77777777777", ("" + count++) + "，idNumber:" + idNumber + "，saveIDString:" + saveIDString);

                            saveIDString = idNumber;//记录身份证信息，
                            idcard_exitTime = System.currentTimeMillis();//记录读取时间
                        }
                    }
                }

                idNumber = "";
            } catch (Exception e) {

                ToastUtil.showToast("身份证读取异常" + e.getMessage());
            }


        } catch (IDCardReaderException e) {
//            textView.setText("读卡失败");
            LogHelper.d("读卡失败, 错误码：" + e.getErrorCode() + "\n错误信息：" + e.getMessage() + "\n 内部错误码=" + e.getInternalErrorCode());
        }
    }

    Runnable word_readIDCard = new Runnable() {
        @Override
        public void run() {

            new Thread(new Runnable() {
                @Override
                public void run() {

                    readIDCard();
                }
            }).start();
//按照当前设置，只能设置为800ms，
// 低于800ms，无法关闭定时任务，会导致其他页面ANR
            handler_work.postDelayed(word_readIDCard, 800);

        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        handler_work.postDelayed(word_readIDCard, 1000);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (writebankcard_mobileedit != null) {
            writebankcard_mobileedit.clearFocus();
        }

        if (handler_work != null) {

            handler_work.removeCallbacks(word_readIDCard);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        openIDReader();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Destroy fingerprint sensor when it's not used


        IDCardReaderFactory.destroy(idCardReader);
        Log.d("idcard", "ma——des");

//        移除扫码监听按钮
        if (mBarcodeScannerResolver != null) {
            mBarcodeScannerResolver.removeScanSuccessListener();
            mBarcodeScannerResolver = null;
        }
        if (mSpeech != null) {
            mSpeech.shutdown();
        }
        if (she != null) {
            she.lightOff();
            she.close();
        }
    }

    /**
     * 扫码枪是输入设备，检测是否有外接输入设备.(这样判断其实并不严格)
     *
     * @return
     */
    private boolean hasScanGun() {
        Configuration cfg = getResources().getConfiguration();
        return cfg.keyboard != Configuration.KEYBOARD_NOKEYS;
    }

//

    /**
     * Activity截获按键事件.发给 BarcodeScannerResolver
     * dispatchKeyEvent() 和 onKeyDown() 方法均可
     *
     * @param event
     * @return
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {

        if (writebankcard_mobileedit != null) {
            writebankcard_mobileedit.setText("");
            writebankcard_mobileedit.clearFocus();
        }
//        Log.i(TAG, "dispatchKeyEvent");

//        if (hasScanGun()) {
//            if (writebankcard_mobileedit!=null) {
//                writebankcard_mobileedit.clearFocus();
//            }
//            mBarcodeScannerResolver.resolveKeyEvent(event);
//        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (writebankcard_mobileedit != null) {
            writebankcard_mobileedit.setText("");
            writebankcard_mobileedit.clearFocus();
        }
        if (mBarcodeScannerResolver != null) {

            mBarcodeScannerResolver.resolveKeyEvent(event);
        }

        return super.onKeyDown(keyCode, event);
    }

    void checkTicket(final String checkType, final String typeData, final String gateNo) {

//        清除记录
        clearText();
        MyProgressUtils.showProgressDialog(MainActivity.this);
        new Thread(new Runnable() {
            @Override
            public void run() {

                // 先封装一个 JSON 对象
                JSONObject param = new JSONObject();

                try {

                    param.put("searchDataType", checkType);
                    param.put("searchData", typeData);
                    param.put("checkCount", checkType == CheckType.TYPE_QRCODE ? -1 : 1);
                    param.put("gateNo", gateNo);
                    param.put("isCollectionGate", "Y");
                    param.put("sign", "A96D48AE69F46BD0E1B17F10316086F3");
                    param.put("timestamp", "20180611165000");


                    String ss = httpUtils.postJson(String.valueOf(SPUtils.get(MainActivity.this, "url", "")) + BaseURL.URL_checkTicket, param);
                    CheckTicketResponse response = new Gson().fromJson(ss, CheckTicketResponse.class);
                    MyProgressUtils.dismissProgress();
                    int result = Integer.valueOf(response.getCode());
                    switch (result) {
                        case 0:
                            setText(response, checkType, typeData);
                            clearText_2s();
                            she.lightGreen();
                            if (response.getData().getPassPersonSum() > 1) {

                                PlayAudioFile(response.getData().getGateSoundName() + response.getData().getPassPersonSum() + "人");
                            } else {

                                PlayAudioFile(response.getData().getGateSoundName());
                            }

                            break;
                        case 100009:
                            Intent intent = new Intent(MainActivity.this, CollectActivity.class);
                            intent.putExtra("caseValue", result);
                            intent.putExtra("checkType", checkType);
                            intent.putExtra("barcodeNo", response.getData().getBarcodeNo());
                            intent.putExtra("typeData", typeData);
                            startActivityForResult(intent, 9);

                            break;
                        case 100010:
                            intent = new Intent(MainActivity.this, CollectActivity.class);
                            intent.putExtra("caseValue", result);
                            intent.putExtra("checkType", checkType);
                            intent.putExtra("typeData", typeData);
                            intent.putExtra("barcodeNo", response.getData().getBarcodeNo());
                            intent.putExtra("rowKey", String.valueOf(response.getData().getRowKey()));
                            intent.putExtra("imgUrl", String.valueOf(response.getData().getImgUrl()));
                            startActivityForResult(intent, 10);


                            break;
                        default:
                            setText(response, checkType, typeData);
                            clearText_2s();
                            she.lightRed();
                            PlayAudioFile(response.getMessage());
                            break;

                    }

                } catch (Exception e) {
                    clearText_2s();
                    ToastUtil.showToast("checkTicket异常：" + e.getMessage());
                }
            }
        }).start();
    }

    void setText(final CheckTicketResponse response, final String checkType, final String typeData) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if (checkType == CheckType.TYPE_IDCARD) {
                    writebankcard_mobileedit.setText(typeData);
                } else {
                    tv_ticketNo.setText(typeData);
                }
                tv_message.setText(response.getMessage());

                if (response.getCode().equals("0")) {

                    tv_count.setText(String.valueOf(response.getData().getPassPersonSum()));

                    img_result.setImageResource(R.drawable.img_check_success_lingtgreen);

                } else {

                    tv_count.setText(String.valueOf("0"));

                    img_result.setImageResource(R.drawable.img_check_fail);
                }
            }
        });
    }

    private void clearText_2s() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                clearText();
            }
        }).start();
    }

    void clearText() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_ticketNo.setText("");
                tv_message.setText("");
                tv_count.setText("");
                writebankcard_mobileedit.setText("");
                img_result.setImageResource(R.drawable.img_check_visible);

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            try {
                String result = data.getStringExtra("message");//得到新Activity 关闭后返回的数据
                String sound = data.getStringExtra("sound");
                String code = data.getStringExtra("code");
                String barCodeNo = data.getStringExtra("barCodeNo");
                if (barCodeNo != null) {
                    tv_ticketNo.setText(barCodeNo);
                }
                tv_message.setText(result);
                if (code.equals("0")) {
                    img_result.setImageResource(R.drawable.img_check_success_lingtgreen);
                    she.lightGreen();

                } else {
                    img_result.setImageResource(R.drawable.img_check_fail);
                    she.lightRed();
                }
                PlayAudioFile(sound);

            } catch (Exception e) {
                ToastUtil.showToast(e.toString());
            } finally {
                clearText_2s();
            }

        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        MyProgressUtils.dismissProgress();
    }
}
